package com.cheyun.netsalev3.utils.api

import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.utils.api.dm.LogInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author Michael
 * @date  2018/11/6 - 14:44.
 */

//object声明单例模式
object DmApiClient {
    /**
     * Http连接超时
     */
    private const val CONNECT_TIMEOUT = 20

    /**
     * Http 读取超时
     */
    private const val READ_TIMEOUT = 20

    /**
     * Http 写入超时
     */
    private const val WRITE_TIMEOUT = 20

    /**
     * 缓存大小
     */
    private const val CACHE_SIZE = 10 * 1024 * 1024

   private fun retrofit(): DmApiStores {
        val cache = Cache(MyApplication.getInstance().cacheDir, CACHE_SIZE.toLong())
        val builder = OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT.toLong(), TimeUnit.SECONDS).readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS)
                .cache(cache)
//        if (BuildConfig.DEBUG) {
//            // Log信息拦截器
//            val loggingInterceptor = HttpLoggingInterceptor()
//            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
//            //设置 Debug Log 模式
//            builder.addInterceptor(loggingInterceptor)
//        }
        builder.addInterceptor(LogInterceptor())
        val okHttpClient = builder.build()
        val retrofit = Retrofit.Builder()
                .baseUrl(DmApiStores.API_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
        //DmApiStores::class.java取得对象的 Java 类
        return retrofit.create(DmApiStores::class.java)
    }

    //用于单例实例化
    @Volatile
    private var instance: DmApiStores? = null

    fun getInstance(): DmApiStores {
        return instance ?: synchronized(this) {
            instance ?: retrofit().also { instance = it }
        }
    }




}

